//
//  LoginViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/4/6.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "LoginViewController.h"

#import "NSString+MD5.h"
#import "RegisterViewController.h"
#import "ForgetViewController.h"
#import "UserTabBarViewController.h"
#import "ShopTabBarViewController.h"
#import <JPUSHService.h>

@interface LoginViewController ()

@property (strong, nonatomic)  UITextField *phoneTextField;   //账号输入
@property (strong, nonatomic)  UITextField *passwordTextField;//密码输入
@property (strong, nonatomic)  UIButton *forgetLabel;          //忘记密码
@property (strong, nonatomic)  UIButton *registerLabel;        //注册
@property (strong, nonatomic)  UIButton *loginBtn;            //登录
Strong UILabel *titleLabel;
Strong UIView *bgView;

@end

@implementation LoginViewController (NetWorking)

 //登录
- (void)login
{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"auMobile":self.phoneTextField.text,@"auPassword":[NSString md5:self.passwordTextField.text]};
    [[AFAppDotNetAPIClient sharedClient] GET:@"logon/logonJudge.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"ResponseStatus"] integerValue] == 0) {
            [UserModel sharedInstanced].userId = [NSString stringWithFormat:@"%@",responseObject[@"obj"][@"auId"]];
            [UserModel sharedInstanced].headImg = [NSString stringWithFormat:@"%@",responseObject[@"obj"][@"auAvatar"]];
            [UserModel sharedInstanced].mobile = responseObject[@"obj"][@"auMobile"];
            [UserModel sharedInstanced].password = responseObject[@"obj"][@"auPassword"];
            [UserModel sharedInstanced].nameNick = responseObject[@"obj"][@"auBuyerNick"];
            [JPUSHService setAlias:[UserModel sharedInstanced].mobile callbackSelector:nil object:nil];
            if ([responseObject[@"obj"][@"auIdentity"] isEqualToString:@"1"]) {
                UserTabBarViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([UserTabBarViewController class])];
                vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                [UserModel sharedInstanced].userType = @"1";
                [UserModel sharedInstanced].address = responseObject[@"obj"][@"auAddress"];
                [self presentViewController:vc animated:YES completion:nil];
            }else{
                ShopTabBarViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([ShopTabBarViewController class])];
                vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                [UserModel sharedInstanced].userType = @"2";
                if (responseObject[@"obj1"]) {
                    [UserModel sharedInstanced].address = responseObject[@"obj1"][@"s_address"];
                    NSString *str = responseObject[@"obj1"][@"s_id"];
                    [UserModel sharedInstanced].s_id = [NSString stringWithFormat:@"%@",str];
                }
                [self presentViewController:vc animated:YES completion:nil];
            }
            
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backEvent)];
    //去掉返回
    [self setupForDismissKeyboard];
    [self.navigationItem setHidesBackButton:YES];
    self.view.backgroundColor = getColor(@"e2f2fc");
    [self.view sd_addSubviews:@[self.bgView , self.titleLabel ,self.registerLabel , self.forgetLabel , self.loginBtn]];
    [self layoutFrame];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setTranslucent:YES];
    [self.navigationController.navigationBar.subviews firstObject].alpha = 0;
    //    [self.navigationController.navigationBar.subviews[0] setAlpha:0];
}

#pragma mark - click

- (void)loginEvent{
    if (![TSRegularExpressionUtil validateMobile:self.phoneTextField.text]) {
        ShowMessage(@"请输入正确的手机号");
        return;
    }
    
    if ([self.passwordTextField.text isEqualToString:@""] ) {
        ShowMessage(@"请输入密码");
        return;
    }
    [self login];
}

- (void)forgetEvent{
    ForgetViewController *vc = [ForgetViewController new];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)registerEvent{
    RegisterViewController *vc = [RegisterViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - set & get

- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [[UIView alloc]initWithFrame:CGRectMake(49 / WIDTH_5S_SCALE, 200 / WIDTH_5S_SCALE, SCREEN_WIDTH - 98 / WIDTH_5S_SCALE, 88  + 1)];
        _bgView.backgroundColor = getColor(@"ffffff");
        _bgView.layer.masksToBounds = YES;
        _bgView.layer.cornerRadius = 5;
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH - 98 / WIDTH_5S_SCALE, 1)];
        lineView.backgroundColor = getColor(@"e2f2fc");
        [_bgView sd_addSubviews:@[self.passwordTextField,self.phoneTextField, lineView]];
    }
    return _bgView;
}

- (UITextField *)phoneTextField{
    if (!_phoneTextField) {
        _phoneTextField  = [[UITextField alloc]init];
        _phoneTextField.font = DEF_FontSize_14;
        _phoneTextField.textColor = getColor(mainColor);
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"用户名" attributes:
                                          @{NSForegroundColorAttributeName:getColor(mainColor)
                                            }];
        _phoneTextField.attributedPlaceholder = attrString;
        _phoneTextField.leftViewMode = UITextFieldViewModeAlways;
        _phoneTextField.leftView = ({
            UIImageView *imgView = [UIImageView new];
            imgView.frame = CGRectMake(0, 8, 50, 16);
            imgView.contentMode = 1;
            imgView.image = [UIImage imageNamed:@"password"];
            imgView;
        });
    }
    return _phoneTextField;
}

- (UITextField *)passwordTextField{
    if (!_passwordTextField) {
        _passwordTextField  = [[UITextField alloc]init];
        _passwordTextField.font = DEF_FontSize_14;
        _passwordTextField.textColor = getColor(mainColor);
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"密码" attributes:
                                          @{NSForegroundColorAttributeName:getColor(mainColor)
                                            }];
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.attributedPlaceholder = attrString;
        _passwordTextField.leftViewMode = UITextFieldViewModeAlways;
        _passwordTextField.leftView = ({
            UIImageView *imgView = [UIImageView new];
            imgView.frame = CGRectMake(0, 8, 50, 16);
            imgView.contentMode = 1;
            imgView.image = [UIImage imageNamed:@"password"];
            imgView;
        });
    }
    return _passwordTextField;
}


- (UIButton *)forgetLabel{
    if (!_forgetLabel) {
        _forgetLabel = [[UIButton alloc]init];
        _forgetLabel.titleLabel.font = DEF_FontSize_14;
        [_forgetLabel setTitle:@"忘记密码？" forState:UIControlStateNormal];
        [_forgetLabel setTitleColor:getColor(mainColor) forState:UIControlStateNormal];
        [_forgetLabel addTarget:self action:@selector(forgetEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    return _forgetLabel;
}

- (UIButton *)registerLabel{
    if (!_registerLabel) {
        _registerLabel = [[UIButton alloc]init];
        _registerLabel.titleLabel.font = DEF_FontSize_14;
        [_registerLabel setTitle:@"注册!" forState:UIControlStateNormal];
        [_registerLabel setTitleColor:getColor(mainColor) forState:UIControlStateNormal];
        [_registerLabel addTarget:self action:@selector(registerEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerLabel;
}

- (UIButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [[UIButton alloc]init];
        _loginBtn.titleLabel.font = DEF_FontSize_14;
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:getColor(@"ffffff") forState:UIControlStateNormal];
        _loginBtn.backgroundColor = getColor(mainColor);
        [_loginBtn addTarget:self action:@selector(loginEvent) forControlEvents:UIControlEventTouchUpInside];
        _loginBtn.layer.masksToBounds = YES;
        _loginBtn.layer.cornerRadius = 5;
    }
    return _loginBtn;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(0, 100 / WIDTH_5S_SCALE, SCREEN_WIDTH, 30 / WIDTH_5S_SCALE)];
        _titleLabel.font = [UIFont systemFontOfSize:50];
        _titleLabel.textColor = getColor(mainColor);
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.text = @"登录";
    }
    return _titleLabel;
}

#pragma mark - layoutFrame

- (void)layoutFrame{
    __weak __typeof(self)weakSelf = self;
    [self.phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    
    [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(weakSelf.phoneTextField.mas_bottom).offset(1);
        make.height.mas_equalTo(44 );
    }];
    
    [self.forgetLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(49 / WIDTH_5S_SCALE);
        make.width.mas_equalTo(70 / WIDTH_5S_SCALE);
        make.top.equalTo(weakSelf.bgView.mas_bottom).offset(5 / WIDTH_5S_SCALE);
        make.height.mas_equalTo(20 / WIDTH_5S_SCALE);
    }];
    
    [self.registerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(- 49 / WIDTH_5S_SCALE);
        make.width.mas_equalTo(40 / WIDTH_5S_SCALE);
        make.top.equalTo(weakSelf.bgView.mas_bottom).offset(5 / WIDTH_5S_SCALE);
        make.height.mas_equalTo(20 / WIDTH_5S_SCALE);
    }];
    
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(- 49 / WIDTH_5S_SCALE);
        make.left.mas_equalTo(49 / WIDTH_5S_SCALE);
        make.top.equalTo(weakSelf.registerLabel.mas_bottom).offset(10 / WIDTH_5S_SCALE);
        make.height.mas_equalTo(35 / WIDTH_5S_SCALE);
    }];
}

@end
